<template>
    <div class="hami-index flex-col"
         :class="{'_has-sidemenu':bShowSidemenu}">
        <slot name="header">
            <!-- 蒙苏智慧工业园区人力资源系统 -->
            <hami-header class="hami-index-top"
                         title=""
                         :userInfo="oUserInfo"
                         @logout-click="fLogout">
                <div class="header-menu-box">
                    <div class="header-menu"
                         v-for="oHeaderMenu in aHeaderMenu"
                         :key="oHeaderMenu.code"
                         :class="{_active: oCurHeaderMenu.code === oHeaderMenu.code}"
                         @click="fHeaderMenuClick(oHeaderMenu)">
                        <!--<div class="header-menu-icon _glrz"></div>-->
                        <div class="header-menu-icon"
                             v-if="oHeaderMenu.ico_class">
                            <span class="iconfont"
                                  :class="oHeaderMenu.ico_class"></span>
                        </div>
                        <div class="header-menu-text">{{oHeaderMenu.name}}</div>
                    </div>
                </div>
            </hami-header>
        </slot>
        <div class="flex-row flex1">
            <!-- 来源：hamigua index -->
            <hami-sidemenu ref="sidemenu"
                           v-if="bShowSidemenu"
                           class="hami-index-sidemenu"
                           :defaultCode="sDefaultCode"
                           :initCollapse="false"
                           @menu-click="fMenuClick"
                           @menu-toggle="fMenuToggle"></hami-sidemenu>
            <div class="flex1">
                <el-tabs class="hami-index-tab"
                         v-model="sCurTab"
                         type="card"
                         v-show="aTabs.length"
                         @tab-click="fTabClick"
                         @tab-remove="fRemoveTab">
                    <el-tab-pane v-for="(oTab) in aTabs"
                                 :key="oTab.code"
                                 :label="oTab.name"
                                 :name="oTab.code"
                                 :closable="oTab.closable !== false">
                        <div slot="label"
                             class="hami-index-tab-label"
                             @contextmenu.stop.prevent="fTabContextMenu(oTab)">
                            {{oTab.name}}
                            <el-dropdown trigger="click"
                                         class="hami-index-tab-dropdown"
                                         placement="bottom"
                                         :ref="'tab-dropdown-' + oTab.code"
                                         @command="fHandleCommand(oTab,...arguments)">
                                <span></span>
                                <el-dropdown-menu slot="dropdown"
                                                  class="hami-index-tab-dropdown-menu">
                                    <el-dropdown-item command="refresh">刷新</el-dropdown-item>
                                    <el-dropdown-item v-if="oTab.closable !== false"
                                                      command="close">关闭</el-dropdown-item>
                                    <el-dropdown-item command="closeOther">关闭其他</el-dropdown-item>
                                    <el-dropdown-item command="closeAll">关闭所有</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </div>
                        <component :is="oTab.router"
                                   class="page"
                                   :key="oTab.key || oTab.code"
                                   :tab="oTab"></component>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
    </div>
</template>
<script>
    import { URLS_COM } from '@/urls';
    import HamiHeader from '@/components/hamigua/header/main.vue';
    import HamiSidemenu from '@/components/hamigua/sidemenu/main.vue';

    const PTCODE = 'HBJC';//菜单CODE
    //const MENU_DATA = [//正式项目中，菜单写死在前端
    //    {
    //        "id": "PRJ-MENU1",
    //        "code": "PRJ-MENU1",
    //        "name": "项目菜单1",
    //        "router": "PRJ/menu1.vue"
    //    },
    //    {
    //        "id": "PRJ-MENU2",
    //        "code": "PRJ-MENU2",
    //        "name": "项目菜单2",
    //        "children": [
    //            {
    //                "id": "PRJ-MENU2-1",
    //                "code": "PRJ-MENU2-1",
    //                "name": "项目菜单2-1",
    //                "router": "PRJ/menu2-1.vue"
    //            }
    //        ]
    //    }
    //];

    export default {
        components: {
            HamiHeader,
            HamiSidemenu
        },
        data() {
            return {
                sDefaultCode: '',//默认选中的菜单 code
                oUserInfo: {},//用户信息
                aHeaderMenu: [],//顶部菜单
                oCurHeaderMenu: {},// 当前选中的顶部菜单
                bShowSidemenu: false,//是否显示左侧菜单
                sCurTab: '', //当前选中的tab
                aTabs: [] //当前打开的tab数组
            }
        },
        mounted() {
            this.G_API.fReqToken().then(() => {
                this.fRequestUserInfo();
            });
            this.$EventBus.$on('tab-add', this.fAddTab);
            this.$EventBus.$on('tab-remove', this.fRemoveTab);
        },
        beforeDestroy() {
            this.$EventBus.$off('tab-add', this.fAddTab);
            this.$EventBus.$off('tab-remove', this.fRemoveTab);
        },
        methods: {
            fLogout() { //登出
                this.G_API.fLogout();
            },
            fAddTab(oMenu) { //新增tab
                let sCode = oMenu.code,
                    bHasTab = false; //是否已经打开该tab
                bHasTab = this.aTabs.some((oTab) => {
                    return oTab.code === sCode;
                });
                if (!bHasTab) { //如果已经打开了该tab，则不添加，直接切换到该tab
                    this.aTabs.push({
                        name: oMenu.name,
                        code: oMenu.code,
                        key: new Date().getTime(),
                        router: oMenu.menuType === 'frame' ? 'hami-' + oMenu.router : oMenu.code,
                        closable: oMenu.closable,
                        auths: (oMenu.auths || []).map((oAuth) => { return oAuth.code }),
                        data: oMenu.data
                    });
                }
                this.sCurTab = oMenu.code;
                this.$EventBus.$emit('tab-change', {
                    name: oMenu.name,
                    code: oMenu.code,
                })
            },
            fRemoveTab(sRemoveTab) { //移除tab
                let aNowTabs = this.aTabs,
                    sCurrentTab = this.sCurTab,
                    sCurrentTabName,
                    oNextTab;
                if (sCurrentTab === sRemoveTab) { //如果删除的是当前tab
                    aNowTabs.forEach((oTab, nTabIdx) => {
                        if (oTab.code === sRemoveTab) {
                            //切换当前tab为后一个或者前一个
                            oNextTab = aNowTabs[nTabIdx + 1] || aNowTabs[nTabIdx - 1];
                            if (oNextTab) {
                                sCurrentTab = oNextTab.code
                                sCurrentTabName = oNextTab.name
                            }
                        }
                    })
                    this.sCurTab = sCurrentTab;
                    this.$EventBus.$emit('tab-change', {
                        name: sCurrentTabName,
                        code: sCurrentTab
                    })
                }
                this.aTabs = aNowTabs.filter(tab => tab.code !== sRemoveTab);
            },
            fTabClick(oTab) {//tab点击
                if (oTab.code !== this.sCurTab) {
                    this.$EventBus.$emit('tab-change', {
                        name: oTab.label,
                        code: oTab.name,
                    })
                }
            },
            fTabContextMenu(oTab) {// tab右键点击
                this.$refs['tab-dropdown-' + oTab.code][0].show();
            },
            fHandleCommand(oTab, sCommand) {// tab右键下拉菜单点击
                let oCurTab;
                switch (sCommand) {
                    case 'close':
                        this.fRemoveTab(oTab.code);
                        break;
                    case 'closeOther':
                        this.aTabs = [oTab];
                        break;
                    case 'closeAll':
                        //删除所有允许关闭的 tab
                        this.aTabs = this.aTabs.filter(oTab => {
                            return oTab.closable === false;
                        });
                        oCurTab = this.aTabs.length ? this.aTabs[0] : {
                            name: '',
                            code: ''
                        };
                        this.sCurTab = oCurTab.code;
                        this.$EventBus.$emit('tab-change', {
                            name: oCurTab.name,
                            code: oCurTab.code
                        });
                        break;
                    case 'refresh':
                        oTab.key = new Date().getTime()
                        break;
                }
            },
            fMenuClick(oMenu) { //菜单点击
                this.fOpenMenu(oMenu);
            },
            fHeaderMenuClick(oHeaderMenu) {//顶部菜单点击
                this.fOpenHeaderMenu(oHeaderMenu);
            },
            fMenuToggle(oMenu) { //菜单分组点击
                //console.log(oMenu)
            },
            fRequestUserInfo() {//请求用户信息
                this.G_API.fReqUserInfo().then(({ data: oData }) => {
                    this.oUserInfo = oData || {}
                    this.fRequestMenu();//用户信息请求成功后再去请求菜单信息
                })
            },
            fRequestMenu() { //请求菜单
                const fMain = (aMenu) => {
                    //菜单数据过滤
                    //aMenu.some((oMenu) => {
                    //    if (oMenu.code === 'VUE') {
                    //        aMenu = oMenu.children;
                    //        return true;
                    //    }
                    //});

                    //加入首页
                    //aMenu.unshift({
                    //    "id": "INDEX-MAIN",
                    //    "code": "INDEX-MAIN",
                    //    "name": "首页",
                    //    "icon": "icon-home-fill",
                    //    "router": "index/main.vue",
                    //    "closable": false
                    //});

                    this.fImportComponents(aMenu);

                    //场景1：顶部导航+左侧菜单
                    this.aHeaderMenu = aMenu;
                    this.fInitMenuSelect();

                    //场景2：只有左侧菜单
                    //this.bShowSidemenu = true;
                    //this.$nextTick(() => {
                    //    this.$refs.sidemenu.fSetMenu(aMenu);
                    //});
                };

                //场景1：项目菜单在前端定义 MENU_DATA
                //if (WISOFT_CONFIG.PROD_DATA) {//此项目后端工程中不配置菜单，在前端写死
                //    fMain(MENU_DATA);
                //}
                //else {
                //    this.$WIV.fRequest({
                //        url: URLS_COM.d_menu,
                //        data: {
                //            ptcode: PTCODE
                //        },
                //    }).then(({ data: res }) => {
                //        if (res && res.length) {
                //            let aMenu = this.fTransSidebarData(res).children;
                //            //前端测试，将本地 demo 菜单请求后合并项目菜单
                //            fMain([...MENU_DATA, ...aMenu]);
                //        }
                //    })
                //}

                //场景2：项目菜单由后端接口返回
                this.$WIV.fRequest({
                    url: URLS_COM.d_menu,
                    data: {
                        ptcode: PTCODE
                    },
                }).then(({ data: res }) => {
                    if (res) {
                        let aMenu = this.fTransSidebarData(res).children;
                        fMain(aMenu);
                    }
                });
            },
            fInitMenuSelect() {//初始化菜单选中状态
                //打开指定的一级菜单
                let nCurHeaderMenuIdx = 0;
                const oUrlParams = this.$WIV.fGetUrlParams(),
                    sDefaultHeader = oUrlParams.menu;
                this.sDefaultCode = oUrlParams.code;
                if (sDefaultHeader) {
                    this.aHeaderMenu.some((oMenu, nMenuIdx) => {
                        if (oMenu.code === sDefaultHeader) {
                            nCurHeaderMenuIdx = nMenuIdx;
                            return true;
                        }
                    })
                }
                this.fOpenHeaderMenu(this.aHeaderMenu[nCurHeaderMenuIdx]);
            },
            fImportComponents(aMenu) { //动态引入组件
                aMenu.map((oMenu) => {
                    if (oMenu.children && oMenu.children.length) {
                        this.fImportComponents(oMenu.children)
                    } else {
                        //数据来源为 hamigua，判断菜单类型
                        //if (oMenu.menuType === 'project') {
                        this.G_API.registerComponent(oMenu);
                        //}
                    }
                })
            },
            fOpenHeaderMenu(oHeaderMenu) {//打开新的顶部菜单
                let aMenu;
                if (this.oCurHeaderMenu.code === oHeaderMenu.code) {
                    return;
                }
                this.aTabs = [];
                this.oCurHeaderMenu = oHeaderMenu;
                aMenu = oHeaderMenu.children;
                if (aMenu && aMenu.length) {
                    this.bShowSidemenu = true;
                    this.$nextTick(() => {
                        this.$refs.sidemenu.fSetMenu(aMenu);
                    })
                }
                else {
                    this.bShowSidemenu = false;
                    this.$nextTick(() => {
                        this.fOpenMenu(this.oCurHeaderMenu);
                    })
                }
            },
            fOpenMenu(oMenu) {//打开新菜单
                //console.log(oMenu)
                if (oMenu.type === 'group') {
                    //分组菜单点击无效
                    return;
                }

                //switch (oMenu.menuType) {
                //    case 'frame':
                //    case 'project':
                this.fAddTab(oMenu);
                //        //this.$HAMI.authority = (oMenu.auths || []).map((oAuth) => { return oAuth.code })
                //        break;
                //    case 'link':
                //        window.open(oMenu.accessaddress)
                //        return;
                //}
            },
            fTransSidebarData(oData) {//处理菜单数据
                //若菜单是本地脚本中写的的静态数据，则需要深拷贝后再处理，否则路由切换再返回时可能出现菜单丢失
                //oData = this.$WIV.fPureClone(oData);//深拷贝数据，防止退出登录后重进时菜单数据变化

                let aChd = oData.children || [],
                    aAms = oData.amsAppList || [];
                let oRst;
                delete oData.children;
                delete oData.amsAppList;

                aChd = aChd.map((oChild) => {
                    return this.fTransSidebarData(oChild);
                })
                aAms.forEach((oAms) => {
                    oAms.code = oAms.appcode ? oAms.appcode : oAms.code;
                    oAms.name = oAms.appname ? oAms.appname : oAms.name;
                    oAms.router = oAms.accessaddress;
                    delete oAms.appcode;
                    delete oAms.appname;
                    delete oAms.accessaddress;
                })

                oRst = {
                    ...oData,
                    children: [...aAms, ...aChd].sort((oItem1, oItem2) => {
                        return oItem1.orderno - oItem2.orderno || 0
                    })
                };
                return oRst;
            },
        }
    };
</script>
<style lang="less">
    //为了覆写 components/hamigua/ 中的组件定义的样式，因此需要在组件引入后引入覆写样式
    @import "~@/assets/css/hamigua.less";

    //覆写 hamigua 样式（from compontents/hamigua）
    .hami-index:not(._has-sidemenu) {
        //不显示菜单的时候隐藏tab头部
        .el-tabs__header {
            display: none;
        }
    }
    .hami-header-title {
        width: 4.5rem;
        background-image: url("~@/assets/images/views/index/index/header-title.png");
    }
</style>
<style lang="less" scope>
    .header-menu-box {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        flex: 1;
        height: 100%;
    }
    .header-menu {
        display: flex;
        align-items: center;
        height: 0.33rem;
        /* line-height: 0.31rem; */
        padding: 0 0.18rem;
        font-size: 0.14rem;
        border: solid 1px #ffffff;
        border-radius: 0.15rem;
        text-align: center;
        cursor: pointer;

        & + & {
            margin-left: 0.2rem;
        }

        &:hover,
        &._active {
            background-color: #48c2f7;
            border-color: #c4f6ff;
        }
    }
    .header-menu-icon {
        //width: 0.24rem;
        //height: 24px;
        //margin: 0 auto 4px;
        //background: center no-repeat;
        //background-size: 100% 100%;
        //&._glrz {
        //    background-image: url("~@/assets/images/views/index/index/header/icon_glrz.png");
        //}
        .iconfont {
            font-size: 12px;
        }
    }
    .header-menu-icon + .header-menu-text {
        margin-left: 4px;
    }
</style>